package com.kcnet.qk.controller.addfriend;

import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.GridView;

import com.kcnet.qk.constant.Const;
import com.kcnet.qk.controller.BasePeopleController;
import com.kcnet.qk.util.NodeUtil;
import com.kcnet.qk.util.PreferenceHelper;
import com.kcnet.qk.util.RootShell;

import org.greenrobot.eventbus.EventBus;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jesse.nativelogger.NLogger;

/**
 * Created by Administrator on 2018/7/9.
 * 添加群好友
 */

public class AddGroupFriendCTR extends BasePeopleController {

    private static String TAG = "添加群好友";

    private int mType;
    private String mClassName;

    private String wxName;

    private static AddGroupFriendCTR mRongCloudInstance;

    protected Map<String, Boolean> mRecordMap = Collections.synchronizedMap(new HashMap());
    protected Map<String, Boolean> namedMap = Collections.synchronizedMap(new HashMap());
    private int maxAddFriend;
    private int currentAddFriend;

    private String text;

    private boolean isBackGroup;

    /**
     * 获取RongCloud 实例。
     *
     * @return RongCloud。
     */
    public static AddGroupFriendCTR getInstance() {
        if (mRongCloudInstance == null) {
            synchronized (AddGroupFriendCTR.class) {

                if (mRongCloudInstance == null) {
                    mRongCloudInstance = new AddGroupFriendCTR();
                }
            }
        }

        return mRongCloudInstance;
    }


    @Override
    public void doTask(AccessibilityEvent event) throws Exception {
        mType = event.getEventType();
        mClassName = (String) event.getClassName();
        if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.LauncherUI)) {
            NLogger.d(TAG, "1.进入微信首页 点击通讯录按钮");
            sleepTime(2000);
            tagTextClick("通讯录");
            sleepTime(1000);
            NLogger.d(TAG, "2.到达通讯录界面 点击 群聊");
            tagTextClick("群聊");
        } else if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.ChatroomContactUI)) {
            NLogger.d(TAG, "3.到达群列表");
            //获取群聊列表
            beginAddPeople();
        } else if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.ChattingUI)) {
            NLogger.d(TAG, "4 进入聊天界面 点击右上角");
            sleepTime(1000);
            if (isBackGroup) {
                RootShell.click(10, 38);
                isBackGroup = false;
            } else {
                RootShell.click(456, 38);
            }

        } else if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.ChatroomInfoUI)) {
            NLogger.d(TAG, "7 进入群详情界面" + isBackGroup);
            sleepTime(1000);
            if (isBackGroup) {
                RootShell.click(10, 38);
            } else {
                beginAddGroup();
            }

        } else if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals("com.tencent.mm.plugin.chatroom.ui.SeeRoomMemberUI")) {
            NLogger.d(TAG, "8 进入群 成员列表界面" + isBackGroup);
            sleepTime(1000);
            beginAddGroupSee();
        } else if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.ContactInfoUI)) {
            NLogger.d(TAG, "8.进入用户资料页面 点击添加按钮");
            peoPleInfoUI();
        } else if (mType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && mClassName.equals(Const.WXUI.SayHiWithSnsPermissionUI)) {
            NLogger.d(TAG, "9.输入好友验证信息 添加好友");
            sleepTimedDefault();
            inputSayHiSentence(text);
            sleepTime(1500);
            RootShell.click(450, 38);
        }
    }

    private void beginAddPeople() {
        AccessibilityNodeInfo scrllorNodeInfo = null;
        AccessibilityNodeInfo root = getRoot();
        if (root != null) {
            scrllorNodeInfo = NodeUtil.findNodeByClassNameAndTime(root, Const.LIST_VIEW, 0);

            for (int i = 0; i < scrllorNodeInfo.getChildCount(); i++) {

                if (currentAddCount == maxAddCount) {
                    currentAddCount = 0;
                    stopTask();
                    return;
                }

                AccessibilityNodeInfo nodeInfo = scrllorNodeInfo.getChild(i);

                if (nodeInfo != null) {
                    List<AccessibilityNodeInfo> nameList = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/aaq");

                    String name = nameList.get(0).getText().toString();

                    if (!mRecordMap.containsKey(name)) {
                        mRecordMap.put(name, true);
                        currentAddCount++;
                        NodeUtil.performClick(nodeInfo);
                        return;

                    }
                    if (i == scrllorNodeInfo.getChildCount() - 1) {
                        NodeUtil.performScroller(scrllorNodeInfo);
                        break;
                    }
                }

            }
        }
    }


    private void peoPleInfoUI() {
        AccessibilityNodeInfo root = getRoot();
        if (root != null) {
            String name ="";
            AccessibilityNodeInfo apx = findTextNodeInfoId("apx");
            if(apx != null){
                 name = apx.getText().toString().trim();
                 name = name.substring(5,name.length());
            }else {
                name = findTextNodeInfoId("qj").getText().toString().trim();
            }
            Log.e(TAG, "peoPleInfoUI" + name);
            if (findTextClick("发消息")) {
                Log.e(TAG, "已经是好友无需添加,点击返回 " + name);
                namedMap.put(name, true);
                performBackClick();
                return;
            }
            if (namedMap.containsKey(name)) {
                Log.e(TAG, "已经是好友无需添加,点击返回 " + name);
                performBackClick();
            } else {

                if (currentAddFriend == maxAddFriend) {
                    currentAddFriend = 0;
                    isBackGroup = true;
                    namedMap.clear();
                    Log.d(TAG, "currentAddFriend " + currentAddFriend + " maxAddFriend :" + maxAddFriend);
                    performBackClick();
                    return;
                }
                namedMap.put(name, true);

                Log.e(TAG, "8.点击添加好友按钮");
                tagTextClick("添加到通讯录");
            }


        }
    }


    private void beginAddGroup() {
        AccessibilityNodeInfo scrllorNodeInfo = null;
        AccessibilityNodeInfo root = getRoot();
        if (root != null) {
            scrllorNodeInfo = NodeUtil.findNodeByClassNameAndTime(root, Const.LIST_VIEW, 0);

            List<AccessibilityNodeInfo> listUser = scrllorNodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/d4d");


            AccessibilityNodeInfo titleNode = root.findAccessibilityNodeInfosByText("聊天信息").get(1);
            String tl = titleNode.getText().toString().trim();
            int size = Integer.valueOf(tl.substring(5, tl.length() - 1));
            Log.d(TAG, "titleNode:" + titleNode.getText().toString());
            if (size >= 44) {
                RootShell.swipe(400, 900, 300, 570);
                sleepTime(800);
                tagTextClick("查看全部群成员");
                return;
            }

            if (listUser.size() < maxAddFriend && currentAddFriend == listUser.size()) {
                Log.d(TAG, "当前群组添加数量小于设定数据 执行返回");
                currentAddFriend = 0;
                isBackGroup = true;
                namedMap.clear();
                performBackClick();
            }
            for (int i = 0; i < listUser.size(); i++) {

                if (currentAddFriend == maxAddFriend) {
                    currentAddFriend = 0;
                    isBackGroup = true;
                    namedMap.clear();
                    Log.d(TAG, "currentAddFriend " + currentAddFriend + " maxAddFriend :" + maxAddFriend);
                    performBackClick();
                    return;
                }
                AccessibilityNodeInfo nodeInfo = listUser.get(i);

                String name = nodeInfo.getText().toString().trim();
                Log.e(TAG, "peoPleInfoUI" + name);
                if (!namedMap.containsKey(name)) {
                    currentAddFriend++;
                    NodeUtil.performClick(nodeInfo);
                    return;

                }
                if (i == listUser.size() - 1) {
                    NodeUtil.performScroller(scrllorNodeInfo);
                    break;
                }
            }

        }

    }

    private void beginAddGroupSee() {
        AccessibilityNodeInfo scrllorNodeInfo = null;

            scrllorNodeInfo = findTextNodeInfoId("d70");
            Log.d(TAG, "scrllorNodeInfo getChildCount" + scrllorNodeInfo.getChildCount());
            for (int i = 0; i < scrllorNodeInfo.getChildCount(); i++) {

                if (currentAddFriend == maxAddFriend) {
                    currentAddFriend = 0;
                    isBackGroup = true;
                    namedMap.clear();
                    performBackClick();
                    return;
                }
                AccessibilityNodeInfo nodeInfo = scrllorNodeInfo.getChild(i);

                String name = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/aja").get(0).getText().toString().trim();
                Log.d(TAG, " beginAddGroupSee name " + name+" "+namedMap.get(name));
                if (!namedMap.containsKey(name)) {
                    currentAddFriend++;
                    NodeUtil.performClick(nodeInfo);
                   return;

                }
                if (i == scrllorNodeInfo.getChildCount() - 1) {
                    NodeUtil.performScroller(scrllorNodeInfo);
                    break;
                }
            }

    }

    /**
     * @param maxAddCount  添加群的数量
     * @param minAddTime
     * @param maxAddTime
     * @param maxAddFriend 添加好友的数量
     * @param text         打招呼文本
     */
    public void setParms(int maxAddCount, int minAddTime, int maxAddTime, int maxAddFriend, String text) {
        //  stopTask();
        EventBus.getDefault().post(new Boolean(true));
        PreferenceHelper.putBoolean(Const.PREF_KEY_STOP_AUTO_FLAG, true);
        this.maxAddCount = maxAddCount;
        this.minAddTime = minAddTime;
        this.maxAddTime = maxAddTime;
        this.currentAddCount = 0;
        this.maxAddFriend = maxAddFriend;
        this.currentAddFriend = 0;
        this.mRecordMap.clear();
        this.namedMap.clear();
        this.text = text;
        this.isBackGroup = false;
    }
}
